//
//  GiftView.m
//  DataSource
//
//  Created by shuihulu02 on 2016/11/29.
//  Copyright © 2016年 大兵布莱恩特. All rights reserved.
//

#import "GiftView.h"
#import "GiftBtn.h"
#import "KeyboardView.h"
#import "UIImage+Gradient.h"
@interface GiftView ()<UIScrollViewDelegate>

// indexPath的数组
@property (strong, nonatomic) NSMutableArray *indexPaths;
// 列数
@property (assign, nonatomic) NSInteger columnNumbers;
@property (nonatomic, strong)UIScrollView* giftScrollView;
@property (nonatomic, strong)GiftBtn* gifBtn;

@property (assign, nonatomic) NSInteger selectIndex;
@property (assign, nonatomic) NSInteger tagIndex;

@end

@implementation GiftView

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];

//        self.backgroundColor = [UIColor blackColor];
//        self.alpha = 0.2;
    }
    
    return self;
}

#pragma mark - 使用UIView的frame的Setter方法
// 此方法是在重新调整视图大小时调用的，可以利用此方法在横竖屏切换时刷新数据使用
- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}
/**
 *  多少列
 *
 *  @return 列
 */
- (NSInteger)columnNumbers
{
    NSInteger number = 1;
    
    if ([self.dataSource respondsToSelector:@selector(numberOfColumnsInWaterFlowView:)])
    {
        number = [self.dataSource numberOfColumnsInWaterFlowView:self];
    }
    _columnNumbers = number;
    
    return _columnNumbers;
    
}
/**
 *  多少行
 *
 *  @return 行数
 */
-(NSInteger)getSections
{
    return 2;
}

- (void)reloadDatasWithBool:(BOOL)isLive
{
    self.isLive = isLive;
    NSInteger count = [self getSections];
    self.tagIndex = 0;
    if (count==0)
    {
        return;
    }
    // 设置 UI 界面
    [self resetView];
}

#pragma mark - 布局视图
// 根据视图属性或数据源方法，生成瀑布流视图界面
- (void)resetView
{
    // 表情总数
    NSInteger dataCount = [self.dataSource numberOfItemsInEmojiView:self];
    // 列数
    NSInteger columnNumber =   [self columnNumbers];
    // 行数
    NSInteger rowCount = [self getSections];
    // 页数
    long pageCount = (dataCount+(rowCount*columnNumber-1))/(rowCount*columnNumber);
    if (self.indexPaths == nil)
    {
        self.indexPaths = [NSMutableArray arrayWithCapacity:dataCount];
    }
    else
    {
        [self.indexPaths removeAllObjects];
    }
    CGFloat y      = 0.0f;
    CGFloat width  = 0.0f;
    CGFloat height = 0.0f;
    CGFloat x      = 0.0f;
    CGFloat space  = 0.0f;
    // 分页控件
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 225, XQScreenW, 10)];
    self.pageControl.numberOfPages = pageCount;
    self.pageControl.currentPage = 0;
    [self addSubview:self.pageControl];
    self.pageControl.currentPageIndicatorTintColor = RGB_HEX(0xffbb01);
    self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    if (pageCount == 1) {
        self.pageControl.hidden = YES;
    }else{
        self.pageControl.hidden = NO;
    }
    if (self.isLive == YES) {
    
        
        UIView *bottomView  = [[UIView alloc] initWithFrame:CGRectMake(0, 240, XQScreenW, 40)];
        bottomView.backgroundColor =  [UIColor colorWithRed:((float)((0xd0101b & 0xFF0000) >> 16))/255.0 green:((float)((0xd0101b & 0xFF00) >> 8))/255.0 blue:((float)(0xd0101b & 0xFF))/255.0 alpha:1.0];
        
        self.numberFlowerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //    [self.deleteBtn  setImage:[UIImage imageNamed:@"DeleteEmoticonBtn@2x.png"] forState:UIControlStateNormal];
        self.numberFlowerBtn.backgroundColor = [UIColor colorWithRed:((float)((0xd0101b & 0xFF0000) >> 16))/255.0 green:((float)((0xd0101b & 0xFF00) >> 8))/255.0 blue:((float)(0xd0101b & 0xFF))/255.0 alpha:1.0];
        self.numberFlowerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.numberFlowerBtn  setFrame:CGRectMake(0, 0, 150, 40)];
        self.numberFlowerBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        
        [self.numberFlowerBtn addTarget:self action:@selector(didNumberBtn:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:self.numberFlowerBtn ];
        
        
        
        self.senderBtn = [UIButton buttonWithType:UIButtonTypeCustom];

        [self.senderBtn  setFrame:CGRectMake(XQScreenW - 120, 0, 110, 40)];
        [self.senderBtn setBackgroundImage:[UIImage gradientImageFromColors:@[HEXCOLOR(0xffc371), HEXCOLOR(0xff5f6d)] frame:self.senderBtn.frame] forState:UIControlStateNormal];

        
        
        [self.senderBtn addTarget:self action:@selector(senderBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:self.senderBtn ];

        [self addSubview:bottomView];
        
    }else {
        self.senderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //    [self.deleteBtn  setImage:[UIImage imageNamed:@"DeleteEmoticonBtn@2x.png"] forState:UIControlStateNormal];
        [self.senderBtn setTitle:@"立即赠送" forState:UIControlStateNormal];
        self.senderBtn.backgroundColor = RGB_HEX(0xFFBB01);
        _senderBtn.layer.cornerRadius = 5;
        self.senderBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.senderBtn  setFrame:CGRectMake(SCREEN_WIDTH-120, 230, 100, 40)];
        [self.senderBtn addTarget:self action:@selector(senderBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.senderBtn ];
        self.beansNumber = [[UIButton alloc]initWithFrame:CGRectMake(20, 230, 60, 40)];
        self.beansNumber.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.beansNumber.titleLabel.textColor = kWhiteColor;
        [self.beansNumber setTitle:@"充值 >" forState:UIControlStateNormal];
        [self addSubview:self.beansNumber];
        [self.beansNumber addTarget:self action:@selector(chargeButton) forControlEvents:UIControlEventTouchUpInside];
    }
    //
    // 创建表情

    self.giftScrollView.frame = CGRectMake(0, 0, XQScreenW, 222);
    _giftScrollView.contentSize = CGSizeMake(pageCount*self.giftScrollView.frame .size.width, 222);
    
    for (NSInteger i = 0; i < pageCount; i++)
    {
        // 放表情的背景
        
        UIView *bgView = [[UIView alloc] init];
//        bgView.backgroundColor = [UIColor whiteColor];
        [ self.giftScrollView addSubview:bgView];
        for (int j =0; j<rowCount*columnNumber; j++)
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.tagIndex inSection:0];
            [self.indexPaths addObject:indexPath];
            GiftBtn *cell = nil;

            if ([self.dataSource respondsToSelector:@selector(GiftView:cellForRowAtIndexPath:)])
            {
                cell = [self.dataSource GiftView:self cellForRowAtIndexPath:indexPath];
                [cell addTarget:self action:@selector(tapClick:) forControlEvents:UIControlEventTouchUpInside];
                cell.tag = self.tagIndex;
            }
//            cell.backgroundColor = [UIColor whiteColor];
            //得到宽 和 高
            width = [self.mydelegate GiftView:self widthForRowAtIndexPath:indexPath];
            
            height= [self.mydelegate GiftView:self heigthForRowAtIndexPath:indexPath];
            //间隔
            space = (self.bounds.size.width-width*columnNumber)/(columnNumber+1);
            // x 和 y 的坐标
            x   = space+(width+space)*(j%columnNumber);
            y   = space+(height+space)*(j/columnNumber);
            
            // 放表情的背景 view
            [cell setFrame:CGRectMake(x,y, width, height)];
            cell.layer.borderColor = [RGBA(220, 220, 220, 0.5) CGColor];;
            cell.layer.borderWidth = 0.35;
            cell.layer.masksToBounds = YES;
            cell.userInteractionEnabled = YES;
            
            [bgView addSubview:cell];
            if (j == 0 && i == 0) {
                [self.gifBtn.selecImage setImage:[UIImage imageNamed:@""]];

                self.gifBtn = cell;

                [self.gifBtn.selecImage setImage:[UIImage imageNamed:@"common_border_gift_s"]];

            }
            [bgView setFrame:CGRectMake(i*self.frame.size.width, 0, self.frame.size.width, y+space+height)];
            if (self.tagIndex<dataCount)
            {
                [cell setNeedsLayout];
                self.tagIndex++;
            }
            else
            {
                [cell removeFromSuperview];
            }
        }
    }
    [self.giftScrollView reloadInputViews];
    self.pagingEnabled = YES;
    self.bounces = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator   = NO;
}
- (UIScrollView*)giftScrollView
{
    if (!_giftScrollView)
    {
        _giftScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _giftScrollView.pagingEnabled = YES;
        _giftScrollView.delegate = self;
        _giftScrollView.showsHorizontalScrollIndicator = NO;
        _giftScrollView.showsVerticalScrollIndicator = NO;
        _giftScrollView.userInteractionEnabled = YES;
        [self addSubview:_giftScrollView];
    }
    return _giftScrollView;
}

- (void)tapClick:(GiftBtn*)tapView
{
    [self.gifBtn.selecImage setImage:[UIImage imageNamed:@""]];
    
    self.gifBtn = tapView;
    [self.gifBtn.selecImage setImage:[UIImage imageNamed:@"common_border_gift_s"]];
    self.gifBtn.selected = NO;
    tapView.selected = YES;
    self.gifBtn = tapView;
    self.selectIndex = tapView.tag;
    
}
/**
 *  展示
 */
-(void)showWithKeyboard:(KeyboardView*)emojiView
{
    self.pageControl.hidden = NO;
    self.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        
        [emojiView setFrame:CGRectMake(0, XQScreenW-40-257, XQScreenW, 40)];
        [self setFrame:CGRectMake(0, XQScreenW-257, XQScreenW, 257)];
    }];
}
/**
 *  隐藏
 */
-(void)hiddenWithKeyboard:(KeyboardView*)emojiView
{
    [UIView animateWithDuration:0.25 animations:^{
        [self setFrame:CGRectMake(0, XQScreenW, XQScreenW, 257)];
        [emojiView setFrame:CGRectMake(0, XQScreenW-40, XQScreenW, 40)];
    }];
    self.selectIndex = 0;
}


/// 赠送的按钮
- (void)senderBtnClick:(UIButton*)deleteBtn
{
    
    
//    BOOL isLogined = [[[NSUserDefaults standardUserDefaults] objectForKey:BMHIsLogined] boolValue];
    
    
//    if (isLogined == NO) {
//        [self.superview removeFromSuperview];
////        [[BMHLoginManager shareInstance] showLoginView];
//
//    }else{
    
        if ([self.mydelegate respondsToSelector:@selector(GiftView:didSelectRowAtIndexPath:)])
        {
            [self.mydelegate GiftView:self didSelectRowAtIndexPath:self.selectIndex];
        }
        
//    }
    
    
    
}
- (void)chargeButton{
    if ([self.mydelegate respondsToSelector:@selector(GiftViewdidSelectChargeBtn)])
    {
        [self.mydelegate GiftViewdidSelectChargeBtn];
    }
}
//玫瑰数按钮
- (void)didNumberBtn :(UIButton *)sender {
    if ([self.mydelegate respondsToSelector:@selector(GiftView:didSelectNumberFlowerBtn:)])
    {
        [self.mydelegate GiftView:self didSelectNumberFlowerBtn:self.selectIndex];
    }

}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = scrollView.contentOffset.x/XQScreenW;
    
}
#pragma mark -  监听 view 的 frame 绝对是否显示 pageControl
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    GiftView *emojiView =(GiftView*)object;
    CGFloat screenHeight = XQScreenW;
    if (screenHeight>emojiView.frame.origin.y)
    {
    }else if (emojiView.frame.origin.y<=XQScreenH)
        {
        }
}
- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"frame" context:nil];
}

@end
